#include <iostream>
#include <cstdio>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
const std::string com_path = "./myfifo";
#define DefaultFd -1
#define Creater 1
#define User 2
#define Read O_RDONLY
#define Write O_WRONLY
#define BaseSize 4096
class NamePiped
{
private:
    bool OpenNamedPipe(int mode)
    {
        _fd = open(_fifo_path.c_str(), mode);
        if (_fd < 0)
        {
            return false;
        }
        return true;
    }

public:
    NamePiped(const std::string &path, int who) : _fifo_path(path), _id(who),_fd(DefaultFd)
    {
        if (_id == Creater)
        {
            int res = mkfifo(_fifo_path.c_str(), 0666);
            if (res != 0)
            {
                perror("mkfifo");
            }
        }
         std::cout << "creater create named pipe" << std::endl;
    }
    bool OpenForRead()
    {
        return OpenNamedPipe(Read);
    }
    bool OpenForWrite()
    {
        return OpenNamedPipe(Write);
    }
    int ReadNamePipe(std::string *out)
    {
        char buffer[BaseSize];
        int n =read(_fd,buffer,sizeof(buffer));//负数表示错误，0表示已经读完写段没了，正数表示成功读取多少字节
        if(n>0)
        {
            buffer[n]=0;//将其变成字符串
            *out=buffer;

        }
        return n;//返回字节数
    }
    int WriteNamedPipe(const std::string &in)
    {
        return write(_fd,in.c_str(),in.size());
    }
    ~NamePiped()
    {
        if (_id == Creater)
        {
            sleep(5);
            int res = unlink(_fifo_path.c_str());
            if (res != 0)
            {
                perror("unlink");
            }
            std::cout << "creater free named pipe" << std::endl;
        }
        if(_fd!=DefaultFd) close(_fd);
    }

private:
    const std::string _fifo_path;//管道的标准路径
    int _id;//用于创世者和成员
    int _fd;//区分读写
};
//这个类中有文件结构体的两个进程；一个读进程，一个写进程


